package com.beta.cust.bind.webapi.config;

import com.beta.cust.bind.webapi.interceptor.BaseInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class SysWebMvcConfig implements WebMvcConfigurer {

    @Autowired
    BaseInterceptor baseInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(baseInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/webapi-docs", "/webapi-docs/**/*", "/index.html", "/fail-message/*", "/index",
                        "/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html");
    }

    //@Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOrigin("*");
        config.setAllowCredentials(true);
        config.addAllowedMethod("*");
        config.addAllowedHeader("*");
        config.addExposedHeader("Access-Control-Allow-Origin");

        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", config);
        return new CorsFilter(configSource);
    }

    @Bean
    public FilterRegistrationBean regCorsFilter() {
        FilterRegistrationBean bean = new FilterRegistrationBean(corsFilter());
        bean.setOrder(0);
        return bean;
    }
}
